package qingxin.dao.impl;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import qingxin.dao.FeedbackDAO;
import qingxin.dbc.DatabaseConnection;
import qingxin.vo.Feedback;

public class FeedbackDAOImpl implements FeedbackDAO {



	public void addWithoutUID(Feedback tip) throws Exception{
		String sql = "insert into feedback (content, date) values (?,?)";
		DatabaseConnection dbc = null;
		try{
			dbc = new DatabaseConnection();
			PreparedStatement pstmt = dbc.getConnection().prepareStatement(sql);
			
			pstmt.setString(1, tip.getContent());
			pstmt.setString(2, tip.getDate());
			
			pstmt.executeUpdate();
		}
		catch(Exception e){
			throw e;
		}
		finally{
			dbc.close();
		}
	}

	@Override
	public void addWithUID(Feedback tip) throws Exception {
		String sql = "insert into feedback (content, date, f_uid) values (?,?,?)";
		DatabaseConnection dbc = null;
		try{
			dbc = new DatabaseConnection();
			PreparedStatement pstmt = dbc.getConnection().prepareStatement(sql);
			
			pstmt.setString(1, tip.getContent());
			pstmt.setString(2, tip.getDate());
			pstmt.setInt(3, tip.getUserID());
			
			pstmt.executeUpdate();
		}
		catch(Exception e){
			throw e;
		}
		finally{
			dbc.close();
		}
		
	}

	@Override
	public Feedback[] getAll(int limit, int start) throws Exception {
		ArrayList<Feedback> feedbacks = new ArrayList<Feedback>();
		String sql = "select fid, content, date, f_uid from feedback where fid < ? " +
				"order by fid desc limit ?";
		DatabaseConnection dbc = new DatabaseConnection();
		try{
			dbc = new DatabaseConnection();
			PreparedStatement pstmt = dbc.getConnection().prepareStatement(sql);
			
			pstmt.setInt(1, start);
			pstmt.setInt(2, limit);
			
			ResultSet rs = pstmt.executeQuery();
			while(rs.next()){
				Feedback feedback = new Feedback();
				feedback.setTipID(rs.getInt(1));
				feedback.setContent(rs.getString(2));
				feedback.setDate(rs.getString(3));
				feedback.setUserID(rs.getInt(4));
				feedbacks.add(feedback);
			}
		}
		catch(Exception e){
			throw e;
		}
		finally{
			dbc.close();
		}
		return feedbacks.toArray(new Feedback[0]);
	}
}
